import os
import re

def process_folder(folder_path):
    """处理单个文件夹内的JPG文件"""
    all_files = os.listdir(folder_path)
    jpg_files = [file for file in all_files if file.lower().endswith('.jpg')]
    to_delete = []

    for file in jpg_files:
        # 匹配以括号数字结尾的文件名（如 image(1).jpg 或 image (2).jpg）
        match = re.match(r'^(.*?)\s*\(\d+\)\.jpg$', file, re.IGNORECASE)
        if match:
            base_name = match.group(1)
            original_file = base_name + '.jpg'
            # 检查是否存在同名原文件（不区分大小写）
            original_exists = any(f.lower() == original_file.lower() for f in jpg_files)
            if original_exists:
                to_delete.append(os.path.join(folder_path, file))

    # 记录并删除文件
    with open('delete.txt', 'a') as f:  # 使用追加模式
        for filepath in to_delete:
            try:
                os.remove(filepath)
                f.write(f"{filepath}\n")
                print(f"已删除: {filepath}")
            except OSError as e:
                print(f"删除失败: {filepath} ({e})")

# 主程序：遍历当前目录下的所有直接子文件夹
current_dir = os.getcwd()
for item in os.listdir(current_dir):
    item_path = os.path.join(current_dir, item)
    if os.path.isdir(item_path):
        print(f"\n处理文件夹: {item}")
        process_folder(item_path)

print("\n操作完成！删除记录已保存到 delete.txt")
